# --
# Copyright (C) 2001-2018 OTRS AG, http://otrs.com/
# --
# This software comes with ABSOLUTELY NO WARRANTY. For details, see
# the enclosed file COPYING for license information (AGPL). If you
# did not receive this file, see http://www.gnu.org/licenses/agpl.txt.
# --

use strict;
use warnings;
use utf8;

use vars (qw($Self));

my $ConfigObject         = $Kernel::OM->Get('Kernel::Config');
my $MainObject           = $Kernel::OM->Get('Kernel::System::Main');
my $ArticleObject        = $Kernel::OM->Get('Kernel::System::Ticket::Article');
my $ArticleBackendObject = $ArticleObject->BackendForChannel( ChannelName => 'Email' );

$Kernel::OM->ObjectParamAdd(
    'Kernel::System::UnitTest::Helper' => {
        RestoreDatabase  => 1,
        UseTmpArticleDir => 1,
    },
);
my $HelperObject = $Kernel::OM->Get('Kernel::System::UnitTest::Helper');

# Disable email addresses checking.
$HelperObject->ConfigSettingChange(
    Key   => 'CheckEmailAddresses',
    Value => 0,
);

my $Success = $ConfigObject->Set(
    Key   => 'SendmailModule',
    Value => 'Kernel::System::Email::Test',
);

$Self->True(
    $Success,
    'Set Email Test backend with true',
);

my $TestEmailObject = $Kernel::OM->Get('Kernel::System::Email::Test');

# testing ArticleSend, especially for bug#8828 (attachments)
# create a ticket first
my $TicketID = $Kernel::OM->Get('Kernel::System::Ticket')->TicketCreate(
    Title        => 'Some Ticket_Title',
    Queue        => 'Raw',
    Lock         => 'unlock',
    Priority     => '3 normal',
    State        => 'closed successful',
    CustomerNo   => '123465',
    CustomerUser => 'customer@example.com',
    OwnerID      => 1,
    UserID       => 1,
);

$Self->True(
    $TicketID,
    'TicketCreate()',
);

# get example attachment data
my $Location       = $ConfigObject->Get('Home') . "/scripts/test/sample/Ticket/Ticket-Article-Test1.pdf";
my $FileContentRef = $MainObject->FileRead(
    Location => $Location,
    Mode     => 'binmode',
);
my $FileContent = ${$FileContentRef};

my @ArticleTests = (
    {
        Name        => 'First article',
        ArticleData => {
            SenderType           => 'agent',
            IsVisibleForCustomer => 1,
            From                 => 'Some Agent <email@example.com>',
            To                   => 'Some Customer A <customer-a@example.com>',
            Subject              => 'some short description',
            Body                 => 'the message text',
            Charset              => 'iso-8859-15',
            MimeType             => 'text/plain',
            Loop                 => 0,
            HistoryType          => 'SendAnswer',
            HistoryComment       => 'Some free text!',
            UserID               => 1,
        },
        ExpectedAttachmentCount => 0,
        ExpectedToArray         => [
            'customer-a@example.com',
        ],
    },
    {
        Name        => 'With base64-encoded image',
        ArticleData => {
            SenderType           => 'agent',
            IsVisibleForCustomer => 1,
            From                 => 'Some Agent <email@example.com>',
            To                   => 'Some Customer A <customer-a@example.com>',
            Subject              => 'some short description',
            Body =>
                '<p>the message text with an image <strong>here</strong>: <img alt="" src="" /> and some more text</p>',
            Charset        => 'iso-8859-15',
            MimeType       => 'text/html',
            Loop           => 0,
            HistoryType    => 'SendAnswer',
            HistoryComment => 'Some free text!',
            UserID         => 1,
        },
        ExpectedAttachmentCount => 1,
        ExpectedToArray         => [
            'customer-a@example.com',
        ],
    },
    {
        Name        => 'With normal attachment (image)',
        ArticleData => {
            SenderType           => 'agent',
            IsVisibleForCustomer => 1,
            From                 => 'Some Agent <email@example.com>',
            To                   => 'Some Customer A <customer-a@example.com>',
            Subject              => 'some short description',
            Body                 => 'the message text',
            Attachment           => [
                {
                    Content     => $FileContent,
                    ContentType => 'application/pdf',
                    Filename    => 'Ticket-Article-Test1.pdf',
                },
            ],
            Charset        => 'iso-8859-15',
            MimeType       => 'text/plain',
            Loop           => 0,
            HistoryType    => 'SendAnswer',
            HistoryComment => 'Some free text!',
            UserID         => 1,
        },
        ExpectedAttachmentCount => 1,
        ExpectedToArray         => [
            'customer-a@example.com',
        ],
    },
);

my %Article;
my $ArticleID;
my %AttachmentIndex;
my $ArticleAttachmentCount;
my $ArticleCount = 0;
my $Emails;
my $Email;
my $MailQueueObj = $Kernel::OM->Get('Kernel::System::MailQueue');

TEST:
for my $Test (@ArticleTests) {

    $Success = $TestEmailObject->CleanUp();
    $Self->True(
        $Success,
        $Test->{Name} . ' - Cleanup Email backend',
    );

    $Self->IsDeeply(
        $TestEmailObject->EmailsGet(),
        [],
        $Test->{Name} . ' - Test backend empty after cleanup',
    );

    # create article
    $ArticleID = $ArticleBackendObject->ArticleSend(
        TicketID => $TicketID,
        %{ $Test->{ArticleData} },
    );

    $Self->True(
        $ArticleID,
        $Test->{Name} . ' - ArticleSend()',
    );

    # Force email queue handling for this object
    my $Item = $MailQueueObj->Get( ArticleID => $ArticleID );
    my $Result = $MailQueueObj->Send( %{$Item} );

    # check that email was sent
    $Emails = $TestEmailObject->EmailsGet();

    # because of cleanup before (see above), there is only one email
    $Self->Is(
        scalar @{$Emails},
        1,
        $Test->{Name} . ' - EmailsGet()',
    );

    # get first (and only) email
    $Email = $Emails->[0];

    $Self->IsDeeply(
        $Email->{ToArray},
        $Test->{ExpectedToArray},
        $Test->{Name} . ' - EmailsGet() To',
    );

    # check article count
    $ArticleCount++;
    $Self->Is(
        scalar $ArticleObject->ArticleList( TicketID => $TicketID ),
        $ArticleCount,
        $Test->{Name} . ' - ArticleCount',
    );

    # check article content
    %Article = $ArticleBackendObject->ArticleGet(
        TicketID  => $TicketID,
        ArticleID => $ArticleID,
    );

    $Self->True(
        $Article{From} eq $Test->{ArticleData}->{From},
        $Test->{Name} . ' - ArticleGet()',
    );

    # check article attachments
    %AttachmentIndex = $ArticleBackendObject->ArticleAttachmentIndex(
        ArticleID        => $ArticleID,
        ExcludePlainText => 1,
        ExcludeHTMLBody  => 1,
    );

    $ArticleAttachmentCount = scalar keys %AttachmentIndex;

    $Self->Is(
        $ArticleAttachmentCount,
        $Test->{ExpectedAttachmentCount},
        $Test->{Name} . ' - Attachment Count'
    );

}

# cleanup is done by RestoreDatabase.

1;
